package com.kfdx.dc.web.controller.system;


import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.file.FileNameUtil;
import com.kfdx.dc.common.core.controller.BaseController;
import com.kfdx.dc.common.core.domain.AjaxResult;
import com.kfdx.dc.common.exception.base.BaseException;
import com.kfdx.dc.framework.web.WebUtils;
import com.kfdx.dc.system.domain.SysFileEntity;
import com.kfdx.dc.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;


/**
 * Oss相关操作接口
 * Created by macro on 2018/4/26.
 */
@RestController
@Api(value = "本地文件上传接口", tags = "本地文件上传接口")
@RequestMapping("/file/local")
public class TeaLocalUploadController extends BaseController {
    @Autowired
    ILocalUploadService localUploadService;
    @Autowired
    ISysFileService fileService;

    @Autowired
    ISysOperLogService logService;
    @Autowired
    ISysUserService userService;
    @Autowired
    ISysDeptService deptService;

    @ApiOperation("单文件上传")
    @ResponseBody
    @PostMapping("/upload")
    public AjaxResult uploadSingleFile(@RequestPart(value = "file", required = true) MultipartFile file, @RequestParam String type) {
        SysFileEntity storageEntity = localUploadService.uploadSingleFile(file, type);
        return AjaxResult.success(storageEntity);
    }

    @ApiOperation("单文件上传")
    @ResponseBody
    @PostMapping("/uploadfile")
    public AjaxResult uploadSingleFileNew(@RequestPart(value = "file", required = true) MultipartFile file, @RequestParam String type) {
        SysFileEntity storageEntity = localUploadService.uploadSingleFileNew(file, type);
        return AjaxResult.success(storageEntity);
    }

    @PostMapping("/uploads")
    @ApiOperation("多文件上传")
    @ResponseBody
    @PreAuthorize("@ss.hasRole('user')")
    public AjaxResult uploadMultiFile(MultipartFile[] multipartFiles, String type) {
        List<SysFileEntity> listTeaResult = localUploadService.uploadMultiFile(multipartFiles, type);

        return AjaxResult.success(listTeaResult);
    }

    @ApiOperation("下载文件")
    @GetMapping("/download/{type}/{time}/{filename}")
    public void downloadFile(HttpServletResponse response, @PathVariable("type") String type, @PathVariable("time") String time, @PathVariable("filename") String filename) {
        WebUtils.setFileDownloadHeader(response, FileNameUtil.getName(filename));
        InputStream inputStream = localUploadService.downloadFile(response, String.format("%s/%s/%s", type, time, filename));


        try {
            IoUtil.copy(inputStream, response.getOutputStream());
        } catch (IOException e) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    @ApiOperation("下载文件")
    @GetMapping("/download1/{fileId}/{uid}")
    public void downloadFile(HttpServletResponse response, @PathVariable(value = "fileId",required = true) Long fileId,@PathVariable(value = "uid",required = true) Long uid) {
        InputStream filePath = localUploadService.downloadFileById(response,fileId);
        if (filePath == null) {
            throw new BaseException("不存在的文件");
        }
        try {
            IoUtil.copy(filePath, response.getOutputStream());
            filePath.close();
        } catch (IOException e) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } finally {
            try {
                filePath.close();
            } catch (IOException e) {
            }
        }
    }

    @ApiOperation("获得文件地址")
    @GetMapping("/get/{fileId}")
    @PreAuthorize("@ss.hasRole('user')")
    public AjaxResult uploadSingleFile(HttpServletResponse response, @PathVariable("fileId") String fileId) {
        String filePath = localUploadService.getFilePathByFileId(fileId);
        AjaxResult success = AjaxResult.success();
        success.put("filePath", filePath);
        return success;
    }
    @ApiOperation("获得文件url")
    @GetMapping("/getUrl/{fileId}")
    public AjaxResult getFileUrl(HttpServletResponse response, @PathVariable("fileId") String fileId) {
        String filePath = localUploadService.getFilePathByFileId(fileId);
        AjaxResult success = AjaxResult.success();
        success.put("filePath", filePath);
        return success;
    }

}
